import {
	HTTP_REQUEST_URL,
} from '@/config/app';

function toLogin() {
	uni.redirectTo({
		url: '/pages/login/login'
	})
}
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false
}) {
	const userId =  uni.getStorageSync('userId')
	const header = {}
	console.log('userId',userId)
	console.log('noAuth',noAuth)

	// 登录过期自动登录
	if (!userId) {
		toLogin();
		return Promise.reject({
			msg: '未登录'
		});
	}

	// header['Token'] = 'Bearer ' + token

	return new Promise((reslove, reject) => {
		uni.request({
			url: HTTP_REQUEST_URL + url,
			method: method || 'GET',
			header: header,
			data: {
				...(data || {}),
				user_id: userId || '1'
			},
			success: (res) => {
				if (res.data.code === 0){
					reslove(res.data, res);
				} else {
					uni.showModal({
						title: '请求失败',
						content: res.data.msg,
						showCancel: false,
						confirmText: 'ok'
					});
					reject(res.data.msg || '系统错误');
				}
			},
			fail: (msg) => {
				let data = {
					mag: '请求失败',
					status: 1 //1没网
				}
				reject(data);
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});


export default request;
